﻿using B.S.BasicData.Infrastructure.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace B.S.BasicData.Infrastructure.Implements
{
    /// <summary>
    /// 仓储接口处理类
    /// </summary>
    /// <typeparam name="T">实体</typeparam>
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        SCDBContext db;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db">数据库上下文</param>
        public BaseRepository(SCDBContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns>返回Sql语句</returns>
        public IQueryable<T> GetAll()
        {
            return db.Set<T>();
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="eneity">要添加的参数</param>
        /// <returns>返回受影响行数</returns>
        public int Add(T eneity)
        {
            db.Set<T>().Add( eneity);   
            return db.SaveChanges();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="eneity">要修改的参数</param>
        /// <returns>返回受影响行数</returns>
        public int Update(T eneity)
        {
            db.Set<T>().Update(eneity);
            return db.SaveChanges();    
        }
        /// <summary>
        /// 查询单个
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>返回受影响行数</returns>
        public T GetById(int id)
        {
            return db.Set<T>().Find(id);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="eneity">要删除的参数</param>
        /// <returns>返回受影响行数</returns>
        public int Delete(T eneity)
        {
            db.Set<T>().Remove(eneity);
            return db.SaveChanges();
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int BatchDeleteByExpress(Expression<Func<T, bool>> expression)
        {
            //用lambda查询
            var entityList = db.Set<T>().Where(expression); //Where(m => m.id == 1)
            db.Set<T>().RemoveRange(entityList);
            return  db.SaveChanges();
        }
    }
}
